package controller;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import model.TDimension;
import model.TDimensionScore;
import model.VScaleTitleType;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;

import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;

import annotation.Log;
import persistent.factory.DAOFactory;
import util.toolkit.Constant;
import util.toolkit.Expression;
import util.toolkit.ResponseJSON;

/**
 * 维度信息管理控制类
 * @author djf
 * @since 2019/2/22
 */
@Controller
@RequestMapping(value = "/dimensionmanagement")
public class SysDimensionManagementController {

	/**
	 * 添加一条量表维度信息
	 * 
	 * @param model
	 * @param req
	 * @param resp
	 * @return
	 * @throws IOException
	 */
	// TODO 添加一条量表维度信息
	@Log(operationType = Constant.OPERTATION_ADD, operationDescribe = "添加一条量表维度信息", operationClassPath = "controller.SysDimensionManagementController.addDimension(Model model,HttpServletRequest req,HttpServletResponse resp)", operationMenu = "量表维度管理/维度信息管理")
	@RequestMapping(value = "/adddimension")
	public String addDimension(Model model, HttpServletRequest req, HttpServletResponse resp) throws IOException {
		req.setCharacterEncoding("utf-8");
		resp.setCharacterEncoding("utf-8");
		resp.setContentType("application/json");

		JSONObject result = new JSONObject();
		TDimension dimension = new TDimension();

		try {
			String dimensionName = req.getParameter("dimensionName"); // 维度名称
			String dimensionDescribe = req.getParameter("dimensionDescribe"); // 维度描述

			if (dimensionName != null && !dimensionName.equals("") && dimensionDescribe != null
					&& !dimensionDescribe.equals("")) {
				dimension.setDimensionName(dimensionName);
				dimension.setDimensionDescribe(dimensionDescribe);
				dimension.setIsDefault("F");

				//TODO 2019-03-06 09:16 徐震霖修改开始
				if (DAOFactory.getIDimensionDAO().addDimension(dimension)) {
				//TODO 2019-03-06 09:16 徐震霖修改结束
					result.put("code", ResponseJSON.FLAG_SUCC);
					result.put("msg", "量表维度添加成功！");
				} else {
					result.put("code", ResponseJSON.FLAG_FAIL);
					result.put("msg", "量表维度添加失败！");
				}
			} else {
				result.put("code", ResponseJSON.FLAG_FAIL);
				result.put("msg", "量表维度添加失败！");
			}
		} catch (Exception e) {
			e.printStackTrace();
			result.put("code", ResponseJSON.FLAG_UNKNOWN_ERORR);
			result.put("msg", "出现未知错误，请联系管理员解决！");
		}
		PrintWriter writer = resp.getWriter();
		writer.print(result);
		return null;
	}
	
	/**
	 * 启用或停用一个维度是否是默认
	 * @param model
	 * @param req
	 * @param resp
	 * @return
	 * @t
	 * hrows IOException
	 */
	//TODO 启用或停用一个维度是否是默认
	@Log(operationType = Constant.OPERTATION_UPDATE, operationDescribe = "启用或停用一个维度是否是默认", 
			operationClassPath = "controller.SysDimensionManagementController.enableOrDisEnableDimension(Model model,HttpServletRequest req,HttpServletResponse resp)", operationMenu = "量表维度管理/维度信息管理")
	@RequestMapping(value = "/enableOrDisEnableDimension")
	public String enableOrDisEnableDimension(Model model, HttpServletRequest req, HttpServletResponse resp) throws IOException {
		req.setCharacterEncoding("utf-8");
		resp.setCharacterEncoding("utf-8");
		resp.setContentType("application/json");

		JSONObject result = new JSONObject();
		
		try {
			String dimensionid = req.getParameter("dimensionid");//维度id
			String status = req.getParameter("status");//维度状态（T为是默认维度，F为不是默认维度）
			if (dimensionid != null && !"".equals(dimensionid) && null != status && !"".equals(status)) {
				TDimension dimension = DAOFactory.getIDimensionDAO().getTDimension(Integer.parseInt(dimensionid));
				if (null == dimension) {
					result.put("code", "0");
					result.put("msg", "未获取到相关维度");
				}
				else {
					dimension.setIsDefault(status);
					if(DAOFactory.getIDimensionDAO().updateDimension(dimension)){
						result.put("code", "1");
						result.put("msg", "设置成功");
					}
					else {
						result.put("code", "0");
						result.put("msg", "设置失败");
					}
				}
			}
			else {
				result.put("code", "0");
				result.put("msg", "维度id或状态不能为空");
			}
		} catch (Exception e) {
			e.printStackTrace();
			result.put("code", ResponseJSON.FLAG_UNKNOWN_ERORR);
			result.put("msg", "出现未知错误，请联系管理员解决！");
		}
		
		PrintWriter writer = resp.getWriter();
		writer.print(result);
		return null;
		
	}

	/**
	 * 删除一个维度信息（如有维度标准分则必须先删除维度标准分）
	 * 
	 * @param model
	 * @param req
	 * @param resp
	 * @return
	 * @throws IOException
	 */
	// TODO 删除一个维度信息（如有维度标准分则必须先删除维度标准分）
	@Log(operationType = Constant.OPERTATION_DELETE, operationDescribe = "删除一个维度信息", operationClassPath = "controller.SysDimensionManagementController.delDimension(Model model,HttpServletRequest req,HttpServletResponse resp)", operationMenu = "量表维度管理/维度信息管理")
	@RequestMapping(value = "/deldimension")
	public String delDimension(Model model, HttpServletRequest req, HttpServletResponse resp) throws IOException {

		req.setCharacterEncoding("utf-8");
		resp.setCharacterEncoding("utf-8");
		resp.setContentType("application/json");

		JSONObject result = new JSONObject();

		try {
			String dimensionid = req.getParameter("dimensionid");

			if (dimensionid != null && !dimensionid.equals("")) {

				Expression exp = new Expression();
				exp.andEqu("dimensionid", dimensionid, Integer.class);
				List<TDimensionScore> scores = DAOFactory.getIDimensionDAO().getDimensionScores(exp.toString());
				if (scores != null && scores.size() > 0) {
					result.put("code", ResponseJSON.FLAG_FAIL);
					result.put("msg", "该量表维度存在评分区间的引用，请先删除评分区间后重试！");
				} else {
					List<VScaleTitleType> titleTypes = DAOFactory.getIScaleTitleTypeDAO()
							.geTScaleTitleTypes(exp.toString());
					if (titleTypes != null && titleTypes.size() > 0) {
						result.put("code", ResponseJSON.FLAG_FAIL);
						result.put("msg", "该量表维度存在卷类信息的引用，请先删除卷类信息后重试！");
					}
					else {
						if (DAOFactory.getIDimensionDAO().deleteDimension(Integer.parseInt(dimensionid))) {
							result.put("code", ResponseJSON.FLAG_SUCC);
							result.put("msg", "量表维度删除成功！");
						} else {
							result.put("code", ResponseJSON.FLAG_FAIL);
							result.put("msg", "量表维度删除失败！");
						}
					}
				}
			} else {
				result.put("code", ResponseJSON.FLAG_FAIL);
				result.put("msg", "量表维度删除失败！");
			}
		} catch (Exception e) {
			e.printStackTrace();
			result.put("code", ResponseJSON.FLAG_UNKNOWN_ERORR);
			result.put("msg", "出现未知错误，请联系管理员解决！");
		}

		PrintWriter writer = resp.getWriter();
		writer.print(result);
		return null;
	}

	/**
	 * 修改量表维度信息
	 * 
	 * @param model
	 * @param req
	 * @param resp
	 * @return
	 * @throws IOException
	 */
	// TODO 修改量表维度信息
	@Log(operationType = Constant.OPERTATION_UPDATE, operationDescribe = "修改一个量表维度信息", operationClassPath = "controller.SysDimensionManagementController.updateDimension(Model model,HttpServletRequest req,HttpServletResponse resp)", operationMenu = "量表维度管理/维度信息管理")
	@RequestMapping(value = "/updatedimension")
	public String updateDimension(Model model, HttpServletRequest req, HttpServletResponse resp) throws IOException {

		req.setCharacterEncoding("utf-8");
		resp.setCharacterEncoding("utf-8");
		resp.setContentType("application/json");

		JSONObject result = new JSONObject();
//		TDimension dimension = new TDimension();

		try {
			String dimensionid = req.getParameter("dimensionid"); // 维度id
			String dimensionName = req.getParameter("dimensionName"); // 维度名称
			String dimensionDescribe = req.getParameter("dimensionDescribe"); // 维度描述

			if (dimensionid != null && !dimensionid.equals("") && dimensionName != null && !dimensionName.equals("")
					&& dimensionDescribe != null && !dimensionDescribe.equals("")) {
				
				TDimension dimension = DAOFactory.getIDimensionDAO().getTDimension(Integer.parseInt(dimensionid));
				
				dimension.setDimensionid(Integer.parseInt(dimensionid));
				dimension.setDimensionName(dimensionName);
				dimension.setDimensionDescribe(dimensionDescribe);
				boolean row = DAOFactory.getIDimensionDAO().updateDimension(dimension);
				if (row) {
					result.put("code", ResponseJSON.FLAG_SUCC);
					result.put("msg", "量表维度修改成功！");
				} else {
					result.put("code", ResponseJSON.FLAG_FAIL);
					result.put("msg", "量表维度修改失败！");
				}
			} else {
				result.put("code", ResponseJSON.FLAG_FAIL);
				result.put("msg", "量表维度修改失败！");
			}
		} catch (Exception e) {
			e.printStackTrace();
			result.put("code", ResponseJSON.FLAG_UNKNOWN_ERORR);
			result.put("msg", "出现未知错误，请联系管理员解决！");
		}

		PrintWriter write = resp.getWriter();
		write.print(result);
		return null;
	}

	/**
	 * 通过查询条件得到量表维度信息列表（不带分页）
	 * 
	 * @param model
	 * @param req
	 * @param resp
	 * @return
	 * @throws IOException
	 */
	// TODO 通过查询条件得到量表维度信息列表（不带分页）
	@Log(operationType = Constant.OPERTATION_QUERY, operationDescribe = "查询量表维度信息", operationClassPath = "controller.SysDimensionManagementController.getAllDimensionList(Model model,HttpServletRequest req,HttpServletResponse resp)", operationMenu = "量表维度管理/维度信息管理")
	@RequestMapping(value = "/getalldimensionlist")
	public String getAllDimensionList(Model model, HttpServletRequest req, HttpServletResponse resp)
			throws IOException {

		req.setCharacterEncoding("utf-8");
		resp.setCharacterEncoding("utf-8");
		resp.setContentType("application/json");

		JSONObject result = new JSONObject();
		Expression exp = new Expression();

		try {
			exp.orderByDesc("dimensionName");
			String strwhere = exp.toString();

			List<TDimension> listsize = DAOFactory.getIDimensionDAO().getDimensions(strwhere);

			if (listsize != null && listsize.size() > 0) {
				result.put("code", 0);
				result.put("msg", "查询成功！");
				result.put("count", listsize.size());
				JSONArray jsonarray = JSONArray.fromObject(listsize);
				result.put("data", jsonarray);
			} else {
				result.put("code", 1);
				result.put("msg", "无查询结果！");
			}
		} catch (Exception e) {
			e.printStackTrace();
			result.put("code", ResponseJSON.FLAG_UNKNOWN_ERORR);
			result.put("msg", "出现未知错误，请联系管理员解决！");
		}

		PrintWriter writer = resp.getWriter();
		writer.print(result);
		return null;
	}

	/**
	 * 通过查询条件得到量表维度信息列表（带分页）
	 * 
	 * @param model
	 * @param req
	 * @param resp
	 * @return
	 * @throws IOException
	 */
	// TODO 通过查询条件得到量表维度信息列表（带分页）
	@Log(operationType = Constant.OPERTATION_QUERY, operationDescribe = "查询量表维度信息", operationClassPath = "controller.SysDimensionManagementController.getDimensionList(Model model,HttpServletRequest req,HttpServletResponse resp)", operationMenu = "量表维度管理/维度信息管理")
	@RequestMapping(value = "/getdimensionlist")
	public String getDimensionList(Model model, HttpServletRequest req, HttpServletResponse resp) throws IOException {

		req.setCharacterEncoding("utf-8");
		resp.setCharacterEncoding("utf-8");
		resp.setContentType("application/json");

		JSONObject result = new JSONObject();
		Expression exp = new Expression();

		try {
			String dimensionname = req.getParameter("dimensionname");
			String currentPage = req.getParameter("page");
			String pageSize = req.getParameter("limit");

			if (currentPage != null && !currentPage.equals("") && pageSize != null && !pageSize.equals("")) {
				if (dimensionname != null) {
					exp.andLike("dimensionName", dimensionname, String.class);
				}
				exp.orderByDesc("dimensionName");

				String strwhere = exp.toString();
				List<TDimension> list = DAOFactory.getIDimensionDAO().getDimensions(strwhere,
						Integer.parseInt(currentPage), Integer.parseInt(pageSize));
				List<TDimension> listsize = DAOFactory.getIDimensionDAO().getDimensions(strwhere);

				if (list != null && list.size() > 0 && listsize.size() > 0) {
					result.put("code", 0);
					result.put("msg", "查询成功！");
					result.put("count", listsize.size());
					JSONArray jsonarray = JSONArray.fromObject(list);
					result.put("data", jsonarray);
				} else {
					result.put("code", 1);
					result.put("msg", "无查询结果！");
				}
			} else {
				result.put("code", 1);
				result.put("msg", "无查询结果！");
			}
		} catch (Exception e) {
			e.printStackTrace();
			result.put("code", ResponseJSON.FLAG_UNKNOWN_ERORR);
			result.put("msg", "出现未知错误，请联系管理员解决！");
		}

		PrintWriter writer = resp.getWriter();
		writer.print(result);
		return null;
	}

	/**
	 * 添加一个维度标准分
	 * 
	 * @param model
	 * @param req
	 * @param resp
	 * @return
	 * @throws IOException
	 */
	// TODO 添加一个维度标准分
	@Log(operationType = Constant.OPERTATION_ADD, operationDescribe = "添加一个维度标准分", operationClassPath = "controller.SysDimensionManagementController.addDimensionScore(Model model,HttpServletRequest req,HttpServletResponse resp)", operationMenu = "量表维度管理/维度信息管理")
	@RequestMapping(value = "/adddimensionscore")
	public String addDimensionScore(Model model, HttpServletRequest req, HttpServletResponse resp) throws IOException {

		req.setCharacterEncoding("utf-8");
		resp.setCharacterEncoding("utf-8");
		resp.setContentType("application/json");

		JSONObject result = new JSONObject();
		TDimensionScore dimensionscore = new TDimensionScore();

		try {
			String dimensionid = req.getParameter("dimensionid");
			String dimensionLev = req.getParameter("dimensionLev");
			String startScore = req.getParameter("startScore");
			String endScore = req.getParameter("endScore");
			String resultDescription = req.getParameter("resultDescription");
			String expertAdvice = req.getParameter("expertAdvice");

			if (dimensionid != null && !dimensionid.equals("") && dimensionLev != null && !dimensionLev.equals("")
					&& startScore != null && !startScore.equals("") && endScore != null && !endScore.equals("")
					&& resultDescription != null && !resultDescription.equals("") && expertAdvice != null
					&& !expertAdvice.equals("")) {
				dimensionscore.setDimensionid(Integer.parseInt(dimensionid));
				dimensionscore.setDimensionLev(dimensionLev);
				dimensionscore.setStartScore(Integer.parseInt(startScore));
				dimensionscore.setEndScore(Integer.parseInt(endScore));
				dimensionscore.setResultDescription(resultDescription);
				dimensionscore.setExpertAdvice(expertAdvice);
				int row = DAOFactory.getIDimensionDAO().addDimensionScore(dimensionscore);
				if (row > 0) {
					result.put("code", ResponseJSON.FLAG_SUCC);
					result.put("msg", "维度标准分添加成功！");
				} else {
					result.put("code", ResponseJSON.FLAG_FAIL);
					result.put("msg", "维度标准分添加失败！");
				}
			} else {
				result.put("code", ResponseJSON.FLAG_FAIL);
				result.put("msg", "维度标准分添加失败！");
			}
		} catch (Exception e) {
			e.printStackTrace();
			result.put("code", ResponseJSON.FLAG_UNKNOWN_ERORR);
			result.put("msg", "出现未知错误，请联系管理员解决！");
		}

		PrintWriter write = resp.getWriter();
		write.print(result);
		return null;
	}

	/**
	 * 删除一个量表维度标准分信息
	 * 
	 * @param model
	 * @param req
	 * @param resp
	 * @return
	 * @throws IOException
	 */
	// TODO 删除一个量表维度标准分信息
	@Log(operationType = Constant.OPERTATION_DELETE, operationDescribe = "删除一个量表维度标准分", operationClassPath = "controller.SysDimensionManagementController.deleteDimensionScore(Model model,HttpServletRequest req,HttpServletResponse resp)", operationMenu = "量表维度管理/维度信息管理")
	@RequestMapping(value = "/deletedimensionscore")
	public String deleteDimensionScore(Model model, HttpServletRequest req, HttpServletResponse resp)
			throws IOException {

		req.setCharacterEncoding("utf-8");
		resp.setCharacterEncoding("utf-8");
		resp.setContentType("application/json");

		JSONObject result = new JSONObject();

		try {
			String scoreid = req.getParameter("scoreid");

			if (scoreid != null && !scoreid.equals("")) {
				boolean row = DAOFactory.getIDimensionDAO().deleteDimensionScore(Integer.parseInt(scoreid));
				if (row) {
					result.put("code", ResponseJSON.FLAG_SUCC);
					result.put("msg", "量表维度标准分删除成功！");
				} else {
					result.put("code", ResponseJSON.FLAG_FAIL);
					result.put("msg", "量表维度标准分删除失败！");
				}
			} else {
				result.put("code", ResponseJSON.FLAG_FAIL);
				result.put("msg", "量表维度标准分删除失败！");
			}
		} catch (Exception e) {
			e.printStackTrace();
			result.put("code", ResponseJSON.FLAG_UNKNOWN_ERORR);
			result.put("msg", "出现未知错误，请联系管理员解决！");
		}
		PrintWriter write = resp.getWriter();
		write.print(result);
		return null;
	}

	/**
	 * 修改量表维度标准分信息
	 * 
	 * @param model
	 * @param req
	 * @param resp
	 * @return
	 * @throws IOException
	 */
	// TODO 修改量表维度标准分信息
	@Log(operationType = Constant.OPERTATION_UPDATE, operationDescribe = "修改一个量表维度标准分", operationClassPath = "controller.SysDimensionManagementController.updateDimensionScore(Model model,HttpServletRequest req,HttpServletResponse resp)", operationMenu = "量表维度管理/维度信息管理")
	@RequestMapping(value = "/updatedimensionscore")
	public String updateDimensionScore(Model model, HttpServletRequest req, HttpServletResponse resp)
			throws IOException {

		req.setCharacterEncoding("utf-8");
		resp.setCharacterEncoding("utf-8");
		resp.setContentType("application/json");

		JSONObject result = new JSONObject();
		TDimensionScore dimensionscore = new TDimensionScore();

		try {
			String scoreid = req.getParameter("scoreid");
			String dimensionLev = req.getParameter("dimensionLev");
			String startScore = req.getParameter("startScore");
			String endScore = req.getParameter("endScore");
			String resultDescription = req.getParameter("resultDescription");
			String expertAdvice = req.getParameter("expertAdvice");

			if (scoreid != null && !scoreid.equals("") && dimensionLev != null && !dimensionLev.equals("")
					&& startScore != null && !startScore.equals("") && endScore != null && !endScore.equals("")
					&& resultDescription != null && !resultDescription.equals("") && expertAdvice != null
					&& !expertAdvice.equals("")) {
				dimensionscore.setId(Integer.parseInt(scoreid));
				dimensionscore.setDimensionLev(dimensionLev);
				dimensionscore.setStartScore(Integer.parseInt(startScore));
				dimensionscore.setEndScore(Integer.parseInt(endScore));
				dimensionscore.setResultDescription(resultDescription);
				dimensionscore.setExpertAdvice(expertAdvice);
				boolean row = DAOFactory.getIDimensionDAO().updateDimensionScore(dimensionscore);
				if (row) {
					result.put("code", ResponseJSON.FLAG_SUCC);
					result.put("msg", "量表维度标准分修改成功！");
				} else {
					result.put("code", ResponseJSON.FLAG_FAIL);
					result.put("msg", "量表维度标准分修改失败！");
				}
			} else {
				result.put("code", ResponseJSON.FLAG_FAIL);
				result.put("msg", "量表维度标准分修改失败！");
			}
		} catch (Exception e) {
			e.printStackTrace();
			result.put("code", ResponseJSON.FLAG_UNKNOWN_ERORR);
			result.put("msg", "出现未知错误，请联系管理员解决！");
		}

		PrintWriter write = resp.getWriter();
		write.print(result);
		return null;
	}

	/**
	 * 获取维度标准分列表（带分页）
	 * 
	 * @param model
	 * @param req
	 * @param resp
	 * @return
	 * @throws IOException
	 */
	// TODO 获取维度标准分列表（带分页）
	@Log(operationType = Constant.OPERTATION_QUERY, operationDescribe = "查询维度标准分", operationClassPath = "controller.SysDimensionManagementController.getDimensionScoreList(Model model,HttpServletRequest req,HttpServletResponse resp)", operationMenu = "量表维度管理/维度信息管理")
	@RequestMapping(value = "/getdimensionscorelist")
	public String getDimensionScoreList(Model model, HttpServletRequest req, HttpServletResponse resp)
			throws IOException {

		req.setCharacterEncoding("utf-8");
		resp.setCharacterEncoding("utf-8");
		resp.setContentType("application/json");

		JSONObject result = new JSONObject();
		Expression exp = new Expression();

		try {
			String dimensionid = req.getParameter("dimensionid");
			String currentPage = req.getParameter("page");
			String pageSize = req.getParameter("limit");

			if (currentPage != null && !currentPage.equals("") && pageSize != null && !pageSize.equals("")) {
				if (dimensionid != null) {
					exp.andEqu("dimensionid", dimensionid, Integer.class);
				}
				exp.orderByDesc("startScore");
				String strwhere = exp.toString();

				List<TDimensionScore> list = DAOFactory.getIDimensionDAO().getDimensionScores(strwhere,
						Integer.parseInt(currentPage), Integer.parseInt(pageSize));
				List<TDimensionScore> listsize = DAOFactory.getIDimensionDAO().getDimensionScores(strwhere);

				if (list != null && list.size() > 0 && listsize.size() > 0) {
					result.put("code", 0);
					result.put("msg", "查询成功！");
					result.put("count", listsize.size());
					JSONArray jsonarray = JSONArray.fromObject(list);
					result.put("data", jsonarray);
				} else {
					result.put("code", 1);
					result.put("msg", "无查询结果！");
				}
			} else {
				result.put("code", 1);
				result.put("msg", "无查询结果！");
			}
		} catch (Exception e) {
			e.printStackTrace();
			result.put("code", ResponseJSON.FLAG_UNKNOWN_ERORR);
			result.put("msg", "出现未知错误，请联系管理员解决！");
		}

		PrintWriter writer = resp.getWriter();
		writer.print(result);
		return null;
	}

}